<!-- src/pagesMember/pages/address/address-form.vue -->
<script setup lang="ts">
import { ref } from 'vue'
import { addAddressApi, getAddressDetailApi, updateAddressApi } from '@/api/address.ts'
import debounce from 'lodash.debounce'
import type { AddressItem } from '@/types/address'

// 表单数据
const form = ref<AddressItem>({
  id: '', // 收货地址 id
  receiver: '', // 收货人
  contact: '', // 联系方式
  fullLocation: '', // 省市区(前端展示，且仅小程序展示)
  provinceCode: '', // 省份编码(后端参数)
  cityCode: '', // 城市编码(后端参数)
  countyCode: '', // 区/县编码(后端参数)
  address: '', // 详细地址
  isDefault: 0, // 默认地址，1为是，0为否
})

const query = defineProps<{ id?: string }>()
uni.setNavigationBarTitle({ title: query.id ? '修改地址' : '新建地址' })

const getAddressDetail = async () => {
  // 获取地址详情
  const res = await getAddressDetailApi(query.id!)
  // 合并数据
  form.value = Object.assign(form.value, res.result)
}

// 如果有 id，则获取地址详情
if (query.id) getAddressDetail()

// #ifdef MP-WEIXIN
const changeRegionWx: UniHelper.RegionPickerOnChange = (e) => {
  form.value.fullLocation = e.detail.value.join(' ')
  const [provinceCode, cityCode, countyCode] = e.detail.code!

  // 合并数据
  Object.assign(form.value, { provinceCode, cityCode, countyCode })
}
// #endif
// #ifdef APP-PLUS || H5
const changeRegionAppH5: UniHelper.UniDataPickerOnChange = (e) => {
  const regions = e.detail.value
  form.value.fullLocation = regions.map((item) => item.text).join(' ')
  const [provinceCode, cityCode, countyCode] = regions.map((item) => item.value)

  // 合并数据
  Object.assign(form.value, { provinceCode, cityCode, countyCode })
}
// #endif

const rules: UniHelper.UniFormsRules = {
  receiver: { rules: [{ required: true, errorMessage: '请填写收货人姓名' }] },
  contact: {
    rules: [
      { required: true, errorMessage: '请填写手机号码' },
      {
        pattern: /^1[3-9]\d{9}$/,
        errorMessage: '手机号格式不正确',
      },
    ],
  },
  fullLocation: {
    rules: [
      {
        required: true,
        errorMessage: '请选择省/市/区(县)',
      },
    ],
  },
  address: {
    rules: [{ required: true, errorMessage: '请填写详细地址' }],
  },
}

const formRef = ref<UniHelper.UniFormsInstance>()

const onSubmit = debounce(async () => {
  // 我都搞不懂 UniHelper 在干什么，为什么把 validate 定义成可选属性，明明就是必有的属性，只能将错就错了
  await formRef.value?.validate!()

  if (query.id) {
    await updateAddressApi(query.id, form.value)
  } else {
    await addAddressApi(form.value)
  }
  uni.showToast({ icon: 'success', title: query.id ? '修改成功' : '添加成功' })

  setTimeout(() => {
    uni.navigateBack()
  }, 1000)
}, 500)
</script>

<template>
  <view class="content">
    <uni-forms :model="form" :rules="rules" ref="formRef">
      <!-- 表单内容 -->
      <uni-forms-item name="receiver" class="form-item">
        <text class="label">收货人</text>
        <input class="input" placeholder="请填写收货人姓名" v-model="form.receiver" />
      </uni-forms-item>
      <uni-forms-item name="contact" class="form-item">
        <text class="label">手机号码</text>
        <input class="input" placeholder="请填写收货人手机号码" v-model="form.contact" />
      </uni-forms-item>
      <uni-forms-item name="fullLocation" class="form-item picker-form-item">
        <text class="label">所在地区</text>
        <!-- #ifdef MP-WEIXIN -->
        <picker
          class="picker"
          mode="region"
          :value="form.fullLocation?.split(' ')"
          @change="changeRegionWx"
        >
          <view v-if="form.fullLocation">{{ form.fullLocation }}</view>
          <view v-else class="placeholder">请选择省/市/区(县)</view>
        </picker>
        <!-- #endif -->
        <!-- #ifdef APP-PLUS || H5 -->
        <uni-data-picker
          :value="form.countyCode"
          class="picker"
          popup-title="请选择城市"
          collection="opendb-city-china"
          field="code as value, name as text"
          orderby="value asc"
          :step-searh="true"
          self-field="code"
          parent-field="parent_code"
          @change="changeRegionAppH5"
        >
          <view v-if="form.fullLocation">{{ form.fullLocation }}</view>
          <view v-else class="placeholder">请选择省/市/区(县)</view>
        </uni-data-picker>
        <!-- #endif -->
      </uni-forms-item>
      <uni-forms-item name="address" class="form-item">
        <text class="label">详细地址</text>
        <input class="input" placeholder="街道、楼牌号等信息" v-model="form.address" />
      </uni-forms-item>
      <uni-forms-item class="form-item">
        <label class="label">设为默认地址</label>
        <switch
          class="switch"
          color="#27ba9b"
          :checked="!!form.isDefault"
          @change="form.isDefault = $event.detail.value ? 1 : 0"
        />
      </uni-forms-item>
    </uni-forms>
  </view>
  <!-- 提交按钮 -->
  <button class="button" @tap="onSubmit">保存并使用</button>
</template>

<style lang="scss">
page {
  background-color: #f4f4f4;
}

.content {
  margin: 20rpx 20rpx 0;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .form-item,
  .uni-forms-item {
    display: flex;
    min-height: 96rpx;
    padding: 25rpx 10rpx 35rpx;
    background-color: #fff;
    border-bottom: 1rpx solid #ddd;
    position: relative;
    margin-bottom: 0;

    // 兼容小程序端，app，H5端
    :deep(.uni-forms-item__label) {
      height: auto;
    }

    // 调整 uni-forms 样式，兼容小程序端，app，H5端
    :deep(.uni-forms-item__content) {
      display: flex;
      font-size: 28rpx;
      align-items: center;
    }

    // 兼容小程序端，app，H5端
    :deep(.uni-forms-item__error) {
      margin-left: 200rpx;
      padding: 0;
    }

    /* #ifdef APP-PLUS || H5 */

    // 处理 uni-data-picker 样式的一个 bug
    :deep(.selected-area) {
      height: auto;
      flex: 0 1 auto;
    }

    /* #endif */

    &:last-child {
      border: none;
    }

    .label {
      width: 200rpx;
      color: #333;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .switch {
      position: absolute;
      top: 50%;
      right: -20rpx;
      transform: translateY(-50%) scale(0.8);
    }

    .picker {
      flex: 1;
    }

    .placeholder {
      color: #808080;
    }
  }
}

.button {
  height: 80rpx;
  margin: 30rpx 20rpx;
  color: #fff;
  border-radius: 80rpx;
  font-size: 30rpx;
  background-color: #27ba9b;
}
</style>
